﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using ChinaScope.CSF.Contract.Entity.CommonEntity;
using ChinaScope.CSF.Contract.Entity.DictEntity;
using ChinaScope.CSF.Contract.Entity.FinancialCommon.MongoModel;
using ChinaScope.CSF.Contract.Entity.FinancialCommon.NormModel;
using MongoDB.Bson;
using TraceItem = ChinaScope.CSF.Contract.Entity.CommonEntity.TraceItem;

namespace ChinaScope.CSF.Contract.Entity.FinancialCommon.FinCommon
{
    public static class Utils
    {
        //public static int CheckFunction(List<int> columnsListForEachQuartor, int beginBindingColNum, int endBindingColuNumForEachQuartor,
        //    int quartorIndex, int yearNum, List<NormStyleItem> CheckItems, Worksheet Sheet,
        //    NormFinRptStyle FinRptStyle)
        //{

        //    CheckItems = UpdateItemsRow(CheckItems, FinRptStyle.items);

        //    for (int columnIndex = beginBindingColNum;
        //         columnIndex <= endBindingColuNumForEachQuartor;
        //         columnIndex++)
        //    {
        //        columnsListForEachQuartor.Add(columnIndex);
        //    }

        //    for (int colIndex = 0; colIndex < columnsListForEachQuartor.Count; colIndex++)
        //    {
        //        foreach (var check in CheckItems)
        //        {
        //            var range = Sheet.Cells[check.Row, columnsListForEachQuartor[colIndex]];
        //            string formula = check.check;

        //            string[] formulas = formula.Split(new char[4] { '+', '-', '*', '/' });
        //            Dictionary<string, string> CodeToValue = new Dictionary<string, string>();

        //            foreach (var code in formulas)
        //            {
        //                NormStyleItem st = FinRptStyle.items.FirstOrDefault(x => x.cd == code);
        //                string value = "0";
        //                //如果check中的code不存在，则给一个默认的0
        //                if (st == null)
        //                {
        //                    value = "0";
        //                }
        //                else
        //                {
        //                    value = GetValue(st, columnsListForEachQuartor[colIndex], Sheet);
        //                }

        //                if (!CodeToValue.ContainsKey(code))
        //                    CodeToValue.Add(code, value);
        //            }

        //            //formula = CodeToValue.Aggregate(formula, (current, cd_v) => current.Replace(cd_v.Key, cd_v.Value));

        //            string rptFinItem = string.Empty;
        //            char[] splitChars = new char[4] { '+', '-', '*', '/' };
        //            StringBuilder newFormula = new StringBuilder();

        //            for (int elementIndex = 0; elementIndex < formula.Length; elementIndex++)
        //            {
        //                if (!splitChars.Contains(formula[elementIndex]))
        //                {
        //                    rptFinItem += formula[elementIndex];
        //                }
        //                else
        //                {
        //                    newFormula.Append(CodeToValue[rptFinItem]);
        //                    newFormula.Append(formula[elementIndex]);
        //                    rptFinItem = "";
        //                }
        //            }

        //            newFormula.Append(CodeToValue[rptFinItem]); //添加最后一个code在新构造的表达式中
        //            formula = newFormula.ToString();

        //            Range checkRange = Sheet.Cells[check.CheckRow, columnsListForEachQuartor[colIndex]];
        //            if (formula.Contains("NA") || formula.Contains("NM"))
        //            {
        //                //checkRange.Value2 = "FALSE";
        //                //checkRange.Interior.Color = Color.Red;

        //                formula = formula.Replace("NA", "0");
        //                formula = formula.Replace("NM", "0");
        //            }
        //            //else
        //            //{
        //            object result = Calc.Eval(formula);

        //            double value2 = 0;
        //            double dbResult = 0;
        //            double number;

        //            if (Double.TryParse(
        //                    Utils.GetCellStrValue(Sheet.Cells[check.Row, columnsListForEachQuartor[colIndex]].Value2),
        //                    out number))
        //            {
        //                value2 = Convert.ToDouble(
        //                    Utils.GetCellStrValue(Sheet.Cells[check.Row, columnsListForEachQuartor[colIndex]].Value2));
        //            }

        //            if (result != null && Double.TryParse(result.ToString(), out number))
        //            {
        //                dbResult = Convert.ToDouble(string.Format("{0:N5}", Convert.ToDouble(result.ToString())));
        //            }

        //            if (
        //                Math.Abs(value2 - dbResult) >
        //                0.0001)
        //            {
        //                checkRange.Value2 = "FALSE";
        //                checkRange.Interior.Color = Color.Red;
        //            }
        //            else
        //            {
        //                checkRange.Value2 = "TRUE";
        //                checkRange.Interior.Color = Color.Green;
        //            }
        //        }

        //        beginBindingColNum = endBindingColuNumForEachQuartor;
        //    }
        //    return beginBindingColNum;
        //}

        public static List<NormStyleItem> UpdateItemsRow(List<NormStyleItem> checkItems, List<NormStyleItem> items)
        {
            foreach (NormStyleItem checkItem in checkItems)
            {
                NormStyleItem findItem = items.Find(x => x.cd == checkItem.cd);

                if (findItem != null)
                    checkItem.Row = items.Find(x => x.cd == checkItem.cd).Row;
            }

            return checkItems;
        }

    //    public static int CheckFunction(List<int> columnsListForEachQuartor, int beginBindingColNum, int endBindingColuNumForEachQuartor,
    //int quartorIndex, int yearNum, List<NormStyleItem> CheckItems, Worksheet Sheet,
    //NormFinSamStyle FinRptStyle)
    //    {

    //        for (int columnIndex = beginBindingColNum;
    //             columnIndex <= endBindingColuNumForEachQuartor;
    //             columnIndex++)
    //        {
    //            columnsListForEachQuartor.Add(columnIndex);
    //        }

    //        for (int colIndex = 0; colIndex < columnsListForEachQuartor.Count; colIndex++)
    //        {
    //            foreach (var check in CheckItems)
    //            {
    //                var range = Sheet.Cells[check.Row, columnsListForEachQuartor[colIndex]];
    //                string formula = check.check;

    //                string[] formulas = formula.Split(new char[4] { '+', '-', '*', '/' });
    //                Dictionary<string, string> CodeToValue = new Dictionary<string, string>();

    //                foreach (var code in formulas)
    //                {
    //                    NormSamStyleItem st = FinRptStyle.items.FirstOrDefault(x => x.cd == code);
    //                    string value = "0";
    //                    //如果check中的code不存在，则给一个默认的0
    //                    if (st == null)
    //                    {
    //                        value = "0";
    //                    }
    //                    else
    //                    {
    //                        value = GetValue(st, columnsListForEachQuartor[colIndex], Sheet);
    //                    }

    //                    if (!CodeToValue.ContainsKey(code))
    //                        CodeToValue.Add(code, value);
    //                }

    //                //formula = CodeToValue.Aggregate(formula, (current, cd_v) => current.Replace(cd_v.Key, cd_v.Value));

    //                string rptFinItem = string.Empty;
    //                char[] splitChars = new char[4] { '+', '-', '*', '/' };
    //                StringBuilder newFormula = new StringBuilder();

    //                for (int elementIndex = 0; elementIndex < formula.Length; elementIndex++)
    //                {
    //                    if (!splitChars.Contains(formula[elementIndex]))
    //                    {
    //                        rptFinItem += formula[elementIndex];
    //                    }
    //                    else
    //                    {
    //                        newFormula.Append(CodeToValue[rptFinItem]);
    //                        newFormula.Append(formula[elementIndex]);
    //                        rptFinItem = "";
    //                    }
    //                }

    //                newFormula.Append(CodeToValue[rptFinItem]); //添加最后一个code在新构造的表达式中
    //                formula = newFormula.ToString();

    //                Range checkRange = Sheet.Cells[check.CheckRow, columnsListForEachQuartor[colIndex]];
    //                if (formula.Contains("NA") || formula.Contains("NM"))
    //                {
    //                    //checkRange.Value2 = "FALSE";
    //                    //checkRange.Interior.Color = Color.Red;

    //                    formula = formula.Replace("NA", "0");
    //                    formula = formula.Replace("NM", "0");
    //                }
    //                //else
    //                //{
    //                object result = Calc.Eval(formula);

    //                double value2 = 0;
    //                double dbResult = 0;
    //                double number;

    //                if (
    //                    Double.TryParse(
    //                        Utils.GetCellStrValue(Sheet.Cells[check.Row, columnsListForEachQuartor[colIndex]].Value2),
    //                        out number))
    //                {
    //                    value2 = Convert.ToDouble(
    //                        Utils.GetCellStrValue(Sheet.Cells[check.Row, columnsListForEachQuartor[colIndex]].Value2));
    //                }

    //                if (result != null && Double.TryParse(result.ToString(), out number))
    //                {
    //                    dbResult = Convert.ToDouble(string.Format("{0:N5}", Convert.ToDouble(result.ToString())));
    //                }

    //                if (
    //                    Math.Abs(value2 - dbResult) >
    //                    0.0001)
    //                {
    //                    checkRange.Value2 = "FALSE";
    //                    checkRange.Interior.Color = Color.Red;
    //                }
    //                else
    //                {
    //                    checkRange.Value2 = "TRUE";
    //                    checkRange.Interior.Color = Color.Green;
    //                }
    //            }

    //            beginBindingColNum = endBindingColuNumForEachQuartor;
    //        }
    //        return beginBindingColNum;
    //    }

        //private static string GetValue(NormStyleItem st, int columnNum, Worksheet Sheet)
        //{
        //    if (Sheet.Cells[st.Row, columnNum].Value2 == null)
        //        return "0";

        //    return Sheet.Cells[st.Row, columnNum].Value2.ToString();//.Text.ToString();修改原因用Text的单元格值如果有小数就直接被忽略了，而Value2可以保留Number类型的小数点值
        //}

        /// <summary>
        /// 获取BsonDocument中元素的值
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="elementName"></param>
        /// <returns></returns>
        public static string GetElementValue(BsonDocument doc, string elementName)
        {
            string result;

            if (!doc.Contains(elementName))
            {
                result = string.Empty;
            }
            else if (doc[elementName] == null)
            {
                result = string.Empty;
            }
            else
            {
                result = doc[elementName].AsString;
            }

            return result;
        }

        //public static string GetFp(string y, string fy)
        //{
        //    try
        //    {
        //        String result = null;

        //        DateTime time = Convert.ToDateTime(y);

        //        int year = time.Year;
        //        int month = time.Month;
        //        int day = time.Day;
        //        //int fyMonth = Convert.ToInt32(fy.Split('-')[0]);
        //        //if ((month - fyMonth) % 3 != 0)
        //        //{
        //        //    return "error parameter";
        //        //}
        //        //else if (month <= fyMonth)
        //        //{
        //        //    //result = year + "Q" + (4 - (fyMonth - month) / 3);
        //        //    result = year.ToString();

        //        //}
        //        //else
        //        //{
        //        //    //result = (year + 1) + "Q" + (month - fyMonth) / 3;
        //        //    result = (year + 1).ToString();
        //        //}
        //        //else
        //        //{
        //        //到fin_fp_temp表中根据fy和y求出fp的一个差值 updateby lh 2013/8/2
        //        string fymonthday = fy;
        //        string ymonthday = string.Format(month + "-" + day);
        //        FinFpTempDao fpdao = new FinFpTempDao();
        //        long fp = FinFpTempDao.GetFpNum(fymonthday, ymonthday);
        //        result = (Convert.ToInt64(year) + fp).ToString();
        //        //}
        //        return result;
        //    }
        //    catch (Exception ex)
        //    {
        //        throw new Exception("计算FP时，出错:" + ex.Message);
        //    }

        //}
        /// <summary>
        /// get the column for current enter quarter
        /// </summary>
        /// <param name="qt"></param>
        /// <param name="quaterColumus"></param>
        /// <returns></returns>
        public static int GetCurQtCol(string qt, QuaterColumus quaterColumus)
        {
            switch (qt.ToLower())
            {
                case "q1":
                    return quaterColumus.Q1; //+ 1;//如果通过面板确定后，Q1原先被隐藏的释放出来，则查询应该从隐藏的那列开始查
                case "q2":
                    return quaterColumus.Q2; // + 1;
                case "q3":
                    return quaterColumus.Q3; // + 1;
                case "q4":
                    return quaterColumus.Q4; // + 1;
            }

            return 0;
        }



        /// <summary>
        /// 填充单元格下拉框的值
        /// </summary>
        /// <param name="range"></param>
        /// <param name="list"></param>
        //public static void AddListEditor(Range range, string list)
        //{
        //    list = Utils.GetCellStrValue(list);
        //    range.Validation.Delete();

        //    if (!string.IsNullOrEmpty(list))
        //    {
        //        range.Validation.Add(XlDVType.xlValidateList, XlDVAlertStyle.xlValidAlertStop, Type.Missing, list,
        //                             Type.Missing);
        //    }

        //}

        /// <summary>
        /// 将字符串数组连接成字符串，并用"，"分隔开
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public static string GetStringList(List<DictModel> list)
        {
            return list.Aggregate<DictModel, string>(null, (current, info) => current + (info.EName + ","));
        }

        /// <summary>
        /// 根据Type将明细表和其他报表的Nature区分开
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public static string GetNatStringList(List<DictModelType> list, string type)
        {
            return list.Where(x => x.TYPE == type).Aggregate<DictModelType, string>(null, (current, info) => current + (info.CName + ","));
        }

        /// <summary>
        /// 【列表转换为字符串】将每个关联项的code和value值，并用"，"分隔开，再用“;”将多个关联项分隔开
        /// </summary>
        /// <param name="list">item的o、l列表字段</param>
        /// <returns>封装的字符串</returns>
        public static string GetStringList(List<TraceItem> list)
        {
            if (list == null || list.Count == 0) { return ""; }
            return list.Aggregate<TraceItem, string>(null, (current, info) => current + (info.Code + "," + info.Value + ";"));
        }

        /// <summary>
        /// 【字符串转换为列表】将每个关联项的code和value值，并用"，"分隔开，再用“;”将多个关联项分隔开
        /// </summary>
        /// <param name="list">item的o、l列表字段</param>
        /// <returns>封装的字符串</returns>
        public static List<TraceItem> GetListString(string combingstr)
        {
            if (string.IsNullOrEmpty(combingstr)) { return null; }
            else
            {
                List<TraceItem> result = new List<TraceItem>();
                string[] traceitems = combingstr.Split(';');
                foreach (string item in traceitems)
                {
                    if (!string.IsNullOrEmpty(item))
                    {
                        string[] traceitem = item.Split(',');
                        if (traceitem.Length >= 2)
                        {
                            TraceItem newitem = new TraceItem();
                            newitem.Code = traceitem[0];
                            newitem.Value = traceitem[1];
                            result.Add(newitem);
                        }
                    }
                }
                return result;
            }
        }

        /// <summary>
        /// 将字符串数组连接成字符串，并用"，"分隔开
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public static string GetStringList(List<MonScale> list)
        {
            return list.Aggregate<MonScale, string>(null, (current, info) => current + (info.EngName + ","));
        }

        /// <summary>
        /// 将字符串数组连接成字符串，并用"，"分隔开
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public static string GetStringListByCode(List<MonScale> list)
        {
            return list.Aggregate<MonScale, string>(null, (current, info) => current + (info.Code + ","));
        }

        /// <summary>
        /// 将Enum类型中的元素名字连接成字符串，并用"，"分隔开
        /// </summary>
        /// <param name="enumType"></param>
        /// <returns></returns>
        public static string CombineStringInEnum(Type enumType)
        {
            string[] enumNamesArr = System.Enum.GetNames(enumType);
            string enumNameStr = string.Empty;

            foreach (string enumName in enumNamesArr)
            {
                enumNameStr += enumName;
                enumNameStr += ",";
            }

            enumNameStr = enumNameStr.TrimEnd(new char[] { ',' });

            return enumNameStr;
        }

        public static string GetStringListForCurrency(List<DictModel> list)
        {
            return list.Aggregate<DictModel, string>(null, (current, info) => current + (info.Code + ","));
        }

        public static string GetCellStrValue(object value)
        {
            string result;

            if (value == null)
            {
                result = "";
            }
            else
            {
                result = value.ToString().Trim();

            }

            return result;
        }

        public static DateTime GetCellDateTimeValue(object value)
        {
            DateTime result;

            if (value == null)
            {
                result = new DateTime();
            }
            else
            {
                result = DateTime.FromOADate((double)value);

            }

            return result;
        }

        public static MonFinItem Createitem(string strRptCode, string tike, string cn, string en, string abbr)
        {
            MonFinItem newitem = new MonFinItem();
            newitem.ItemCode = Utils.CreateGuidCode(strRptCode); //"is_rep_codenew";//TODO:需要自己构造
            newitem.CurrencyTrans = true;
            newitem.Digit = 0;
            newitem.Nat = null;
            newitem.Parent = null;
            newitem.RelationSet = new List<string>(); //初始化的关联关系暂时为空，之后再做自关联关系       
            newitem.Remark = null;
            newitem.Rpt = strRptCode;
            newitem.SecurtyCode = "";
            newitem.Suffix = "";
            newitem.Tik = tike; //查询的tiker值         

            newitem.TraceType = "1";
            newitem.TransName = new MonName { ChinName = cn, EngName = en, Abrev = abbr }; //此值会在后面修改
            newitem.UnitTrans = true;

            return newitem;
        }

        public static bool GetCellBoolValue(object value)
        {
            bool result = false;

            if (value == null)
            {
                result = false;
            }
            else
            {
                result = Convert.ToBoolean(value.ToString());

            }

            return result;
        }

        public static bool GetCellBoolValueOnString(object value)
        {
            bool result = false;

            if (value == null)
            {
                result = false;
            }
            else
            {
                if (value.ToString().ToLower() == "yes")
                    result = true;
                if (value.ToString().ToLower() == "no")
                    result = false;
            }

            return result;
        }

        public static int GetCellIntValueOnString(object value)
        {
            int result = 0;

            if (value == null)
            {
                result = 0;
            }
            else
            {
                if (value.ToString().ToLower() == "yes")
                    result = 1;
                if (value.ToString().ToLower() == "no")
                    result = 0;
            }

            return result;
        }

        public static int GetCellIntValue(object value)
        {
            int result = value == null ? 0 : Convert.ToInt32(value);

            return result;
        }

        /// <summary>
        /// 依据科目级别(Level)放在不同的列
        /// </summary>
        /// <param name="level"></param>
        /// <returns></returns>
        public static string GetItemOnCol(long level)
        {
            switch (level)
            {
                case 1:
                    return CommonTemplateConfigure.ItemLevel1Col;
                case 2:
                    return CommonTemplateConfigure.ItemLevel2Col;
                case 3:
                    return CommonTemplateConfigure.ItemLevel3Col;
                case 4:
                    return CommonTemplateConfigure.ItemLevel4Col;
                case 5:
                    return CommonTemplateConfigure.ItemLevel5Col;
                case 6:
                    return CommonTemplateConfigure.ItemLevel6Col;
                case 7:
                    return CommonTemplateConfigure.ItemLevel7Col;
            }
            return CommonTemplateConfigure.ItemLevel1Col;
        }


        /// <summary>
        /// 依据科目级别(Level)放在不同的列
        /// </summary>
        /// <param name="level"></param>
        /// <returns></returns>
        public static string GetTplItemOnCol(long level)
        {
            switch (level)
            {
                case 1:
                    return CommonTemplateConfigure.CURItemLevel1Col;
                case 2:
                    return CommonTemplateConfigure.CURItemLevel2Col;
                case 3:
                    return CommonTemplateConfigure.CURItemLevel3Col;
                case 4:
                    return CommonTemplateConfigure.CURItemLevel4Col;
                case 5:
                    return CommonTemplateConfigure.CURItemLevel5Col;
                case 6:
                    return CommonTemplateConfigure.CURItemLevel6Col;
                case 7:
                    return CommonTemplateConfigure.CURItemLevel7Col;
            }
            return CommonTemplateConfigure.CURItemLevel1Col;
        }

        /// <summary>
        /// LTM依据科目级别(Level)放在不同的列
        /// </summary>
        /// <param name="level"></param>
        /// <returns></returns>
        public static string GetItemOnColForLTM(long level)
        {
            switch (level)
            {
                case 1:
                    return CommonTemplateConfigure.LTMItemLevel1Col;
                case 2:
                    return CommonTemplateConfigure.LTMItemLevel2Col;
                case 3:
                    return CommonTemplateConfigure.LTMItemLevel3Col;
                case 4:
                    return CommonTemplateConfigure.LTMItemLevel4Col;
                case 5:
                    return CommonTemplateConfigure.LTMItemLevel5Col;
                case 6:
                    return CommonTemplateConfigure.ItemLevel1Col;
                case 7:
                    return CommonTemplateConfigure.ItemLevel2Col;
            }
            return CommonTemplateConfigure.LTMItemLevel1Col;
        }

        /// <summary>
        /// CUR依据科目级别(Level)放在不同的列
        /// </summary>
        /// <param name="level"></param>
        /// <returns></returns>
        public static string GetItemOnColForCUR(long level)
        {
            switch (level)
            {
                case 1:
                    return CommonTemplateConfigure.CURItemLevel1Col;
                case 2:
                    return CommonTemplateConfigure.CURItemLevel2Col;
                case 3:
                    return CommonTemplateConfigure.CURItemLevel3Col;
                case 4:
                    return CommonTemplateConfigure.CURItemLevel4Col;
                case 5:
                    return CommonTemplateConfigure.CURItemLevel5Col;
                case 6:
                    return CommonTemplateConfigure.CURItemLevel6Col;
                case 7:
                    return CommonTemplateConfigure.CURItemLevel7Col;
            }
            return CommonTemplateConfigure.CURItemLevel1Col;
        }

        /// <summary>
        /// 给Excel中的Range添加Style
        /// </summary>
        /// <param name="argRange"></param>
        /// <param name="level"></param>
        /// <param name="book"></param>
        //public static void ApplyStyle(Range argRange, long argLevel, Workbook argBook)
        //{
        //    StyleUtils.TempWorkBook = argBook;

        //    switch (argLevel)
        //    {
        //        case 1:
        //            argRange.Style = StyleUtils.ItemLevel1;
        //            break;
        //        case 2:
        //            argRange.Style = StyleUtils.ItemLevel2;
        //            break;
        //        case 3:
        //            argRange.Style = StyleUtils.ItemLevel3;
        //            break;
        //        case 4:
        //            argRange.Style = StyleUtils.ItemLevel4;
        //            break;
        //        case 5:
        //            argRange.Style = StyleUtils.ItemLevel5;
        //            break;
        //        case 6:
        //            argRange.Style = StyleUtils.ItemLevel6;
        //            break;
        //        case 7:
        //            argRange.Style = StyleUtils.ItemLevel7;
        //            break;
        //        default:
        //            argRange.Style = StyleUtils.ItemLevel1;
        //            break;
        //    }
        //}


        /// <summary>
        /// 给Excel中的Range添加Style
        /// </summary>
        /// <param name="argRange"></param>
        /// <param name="level"></param>
        /// <param name="book"></param>
        //public static void ApplySZStyle(Range argSZRange, long argLevel, Workbook argBook)
        //{
        //    try
        //    {
        //        StyleUtils.TempWorkBook = argBook;
        //        switch (argLevel)
        //        {
        //            case 1:
        //                argSZRange.Style = StyleUtils.ItemSZLevel1;
        //                break;
        //            case 2:
        //                argSZRange.Style = StyleUtils.ItemSZLevel2;
        //                break;
        //            case 3:
        //                argSZRange.Style = StyleUtils.ItemSZLevel3;
        //                break;
        //            case 4:
        //                argSZRange.Style = StyleUtils.ItemSZLevel4;
        //                break;
        //            case 5:
        //                argSZRange.Style = StyleUtils.ItemSZLevel5;
        //                break;
        //            case 6:
        //                argSZRange.Style = StyleUtils.ItemSZLevel6;
        //                break;
        //            case 7:
        //                argSZRange.Style = StyleUtils.ItemSZLevel7;
        //                break;
        //            default:
        //                argSZRange.Style = StyleUtils.ItemSZLevel1;
        //                break;
        //        }
        //    }
        //    catch (Exception)
        //    {
        //    }
        //}

        /// <summary>
        /// 填充（几年）的数据到单元格下拉框(表头历史数据上方)
        /// </summary>
        /// <param name="rowIndex">绑定所在行</param>
        /// <param name="firstColForBindingData">绑定数据的开始列</param>
        /// <param name="severalYears">显示多少年的数据</param>
        /// <param name="entities">填充的字符串(包含',')</param>
        /// <param name="worksheet">worksheet</param>
        /// <param name="isDisplayDefaultText">是否显示默认值</param>
        /// <param name="defaultDisplayText">默认值</param>
        //public static void BindingDataToList(int rowIndex, int firstColForBindingData, int severalYears, string entities,
        //                                     Worksheet worksheet, bool isDisplayDefaultText, string defaultDisplayText)
        //{
        //    int beginBindingColNum = firstColForBindingData;
        //    int endBindingColuNumForEachQuartor = 0;
        //    Range range = null;

        //    //四期数据
        //    for (int quartorIndex = 0; quartorIndex < CommonTemplateConfigure.AccountQuartors; quartorIndex++)
        //    {
        //        //不是第一期数据
        //        if (quartorIndex != 0)
        //        {
        //            //填充的起始列前面有两列,因为每期隔一列
        //            beginBindingColNum += 2;
        //        }

        //        endBindingColuNumForEachQuartor = beginBindingColNum;
        //        endBindingColuNumForEachQuartor += severalYears;
        //        range = worksheet.Range[worksheet.Cells[rowIndex, beginBindingColNum],
        //                                worksheet.Cells[rowIndex, endBindingColuNumForEachQuartor]];
        //        beginBindingColNum = endBindingColuNumForEachQuartor;

        //        Utils.AddListEditor(range, entities);
        //        if (isDisplayDefaultText)
        //        {
        //            range.Value2 = defaultDisplayText;
        //        }
        //    }
        //}

        /// <summary>
        /// 隐藏各期的前面一列
        /// </summary>
        /// <param name="accountYears"></param>
        /// <param name="worksheet"></param>
        /// <param name="firstHideColumn"></param>
        //public static void HideTheFirstColOfEachQuartor(int accountYears, Worksheet worksheet, int firstHideColumn)
        //{
        //    int beginBindingColNum = firstHideColumn;

        //    for (int quartorIndex = 0; quartorIndex < CommonTemplateConfigure.AccountQuartors; quartorIndex++)
        //    {
        //        if (quartorIndex == 0)
        //        {
        //            worksheet.Cells[1, beginBindingColNum].EntireColumn.Hidden = true;
        //        }
        //        else
        //        {
        //            beginBindingColNum += accountYears;
        //            beginBindingColNum += 2;
        //            worksheet.Cells[1, beginBindingColNum].EntireColumn.Hidden = true;
        //        }
        //    }
        //}

        /// <summary>
        /// 在WorkSheet中添加或删除列
        /// </summary>
        /// <param name="countYears"></param>
        /// <param name="prevousCountYears"></param>
        /// <param name="worksheet"></param>
        /// <param name="firstDelCol"></param>
        //public static void AddOrDeleteColumnToWorkSheet(int countYears, int prevousCountYears, Worksheet worksheet,
        //                                                int firstDelCol)
        //{
        //    int beginBindingColNum = firstDelCol;

        //    if (countYears == prevousCountYears)
        //    {
        //        return;
        //    }
        //    if (worksheet.Name == "2.1.1")
        //    {
        //        //每期
        //        for (int quartorIndex = 0; quartorIndex < CommonTemplateConfigure.AccountQuartors; quartorIndex++)
        //        {
        //            //不是第一期数据
        //            if (quartorIndex != 0)
        //            {
        //                //填充的起始列前面有两列,因为每期隔一列，隐藏一列
        //                beginBindingColNum += 2;
        //            }

        //            //添加列
        //            if (countYears > prevousCountYears)
        //            {
        //                for (int i = 0; i < countYears - prevousCountYears; i++)
        //                {
        //                    //在每期最后一列插入列
        //                    worksheet.Cells[1, beginBindingColNum + prevousCountYears].EntireColumn.Insert(
        //                        Shift: XlInsertShiftDirection.xlShiftToRight);
        //                }

        //                beginBindingColNum += countYears;
        //            }

        //            //删除列
        //            if (countYears < prevousCountYears)
        //            {
        //                for (int i = 0; i < prevousCountYears - countYears; i++)
        //                {
        //                    worksheet.Cells[1, beginBindingColNum + 1].EntireColumn.Delete(
        //                        Shift: XlDeleteShiftDirection.xlShiftToLeft);
        //                }
        //                beginBindingColNum += countYears;
        //            }
        //        }
        //    }
        //    else
        //    {
        //        AddOrDelColForCURTpl(countYears, prevousCountYears, worksheet, beginBindingColNum);
        //    }
        //}


        /// <summary>
        /// 将Excel的列的数字序列转化为字母
        /// </summary>
        /// <param name="columnNumber"></param>
        /// <returns></returns>
        public static string GetExcelColumnName(int columnNumber)
        {
            int dividend = columnNumber;
            string columnName = String.Empty;
            int modulo;

            while (dividend > 0)
            {
                modulo = (dividend - 1) % 26;
                columnName = Convert.ToChar(65 + modulo).ToString() + columnName;
                dividend = (int)((dividend - modulo) / 26);
            }

            return columnName;
        }

        /// <summary>
        /// 把EXCEL的列名转成整数数字
        /// </summary>
        /// <param name="argCol">列名</param>
        /// <returns>列名整数</returns>
        public static int GetExcelColToInt(String argCol)
        {
            if (!Regex.IsMatch(argCol.ToUpper(), @"[A-Z]+"))
            {
                throw new Exception("Invalid parameter");
            }
            int index = 0;
            char[] chars = argCol.ToUpper().ToCharArray();
            for (int i = 0; i < chars.Length; i++)
            {
                index += ((int)chars[i] - (int)'A' + 1) * (int)Math.Pow(26, chars.Length - i - 1);
            }
            return index;
        }

        /// <summary>
        /// 针对首行隐藏了样式列的模版进行删除和添加列
        /// </summary>
        //private static void AddOrDelColForCURTpl(int countYears, int prevousCountYears, Worksheet worksheet,
        //                                         int beginBindingColNum)
        //{

        //    for (int quartorIndex = 0; quartorIndex < CommonTemplateConfigure.AccountQuartors; quartorIndex++)
        //    {
        //        //不是第一期数据
        //        if (quartorIndex != 0)
        //        {
        //            //填充的起始列前面有两列,因为每期隔一列，隐藏一列
        //            beginBindingColNum += 2;
        //        }

        //        //添加列
        //        if (countYears > prevousCountYears)
        //        {
        //            for (int i = 0; i < countYears - prevousCountYears; i++)
        //            {
        //                //在每期最后一列的前一列插入列保证样式
        //                worksheet.Cells[1, beginBindingColNum + prevousCountYears - 1].EntireColumn.Insert(
        //                    Shift: XlInsertShiftDirection.xlShiftToRight);
        //                //为添加行添加验证公式                    
        //                string formula = MadeUI.FormulaStr(beginBindingColNum + prevousCountYears - 1,
        //                                                   TemplateConfigure.LTMContentRow,
        //                                                   TemplateConfigure.LTMStartRow, TemplateConfigure.CURTplEndRow,
        //                                                   TemplateConfigure.formulaValidRows);
        //                worksheet.Cells[TemplateConfigure.LTMShowBindRow, beginBindingColNum + prevousCountYears - 1].
        //                    Formula = formula;

        //            }

        //            beginBindingColNum += countYears;
        //        }

        //        //删除列
        //        if (countYears < prevousCountYears)
        //        {
        //            for (int i = 0; i < prevousCountYears - countYears; i++)
        //            {
        //                worksheet.Cells[1, beginBindingColNum].EntireColumn.Delete(
        //                    Shift: XlDeleteShiftDirection.xlShiftToLeft);
        //            }
        //            beginBindingColNum += countYears;
        //        }
        //    }
        //}

        /// <summary>
        /// 将枚举转换为字符串
        /// </summary>
        /// <param name="value">枚举</param>
        /// <returns>自定义字符串</returns>
        public static string GetDescription(Enum value)
        {
            FieldInfo field = value.GetType().GetField(value.ToString());
            DescriptionAttribute[] attributes =
                (DescriptionAttribute[])field.GetCustomAttributes(typeof(DescriptionAttribute), false);
            return (attributes.Length > 0) ? attributes[0].Description : value.ToString();
        }

        public static bool IsDataValid(object value)
        {
            try
            {
                Convert.ToDouble(value);
                return true;
            }
            catch (Exception)
            {
                if (value.ToString().ToLower() == "na" || value.ToString().ToLower() == "nm" || value == "")
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        public static bool IsNumber(String strNumber)
        {
            Regex objNotNumberPattern = new Regex("[^0-9.-]");
            Regex objTwoDotPattern = new Regex("[0-9]*[.][0-9]*[.][0-9]*");
            Regex objTwoMinusPattern = new Regex("[0-9]*[-][0-9]*[-][0-9]*");
            String strValidRealPattern = "^([-]|[.]|[-.]|[0-9])[0-9]*[.]*[0-9]+$";
            String strValidIntegerPattern = "^([-]|[0-9])[0-9]*$";
            Regex objNumberPattern = new Regex("(" + strValidRealPattern + ")|(" + strValidIntegerPattern + ")");
            return !objNotNumberPattern.IsMatch(strNumber) &&
                   !objTwoDotPattern.IsMatch(strNumber) &&
                   !objTwoMinusPattern.IsMatch(strNumber) &&
                   objNumberPattern.IsMatch(strNumber);
        }

        /// <summary>
        /// 将列拼接特定字符串（所有模版均有该字符串提示，提取出来通用）
        /// </summary>
        /// <returns></returns>
        public static string GiveColTips(List<string> SameColRecord)
        {
            string tips = "";
            foreach (var item in SameColRecord)
            {
                tips += item + "列 ";
            }
            return tips;
        }

        /// <summary>
        /// 将字符串时间转换成DateTime格式 用于排序 如果是NULL 则返回 0001/0/0 
        /// </summary>
        /// <param name="argDateTime">时间字符串</param>
        /// <returns>DateTime 类型时间</returns>
        public static DateTime StringToDateTime(string argDateTime)
        {
            if (string.IsNullOrEmpty(argDateTime))
            {
                return new DateTime();
            }
            else
            {
                try
                {
                    return DateTime.Parse(argDateTime);
                }
                catch (Exception)
                {
                    string strMeeage = "时间格式不正确!";
                    throw new Exception(strMeeage);
                }

            }
        }


        /// <summary>
        /// create item code
        /// </summary>  
        public static string CreateGuidCode(string rpt)
        {
            long i = 1;
            foreach (byte b in Guid.NewGuid().ToByteArray())
            {
                i *= ((int)b + 1);
            }
            return string.Format("{0:x}", i - DateTime.Now.Ticks);
        }

        public static MonRemark GetComments(object text)
        {
            MonRemark remark = new MonRemark();

            try
            {
                if (text != null && text.ToString() != "")
                {
                    int index = text.ToString().IndexOf("英文备注", System.StringComparison.Ordinal);

                    string cn = text.ToString().Substring(5, index - 7);

                    string en = text.ToString().Substring(index + 5, text.ToString().Length - index - 5);

                    remark.szh = cn;
                    remark.en = en;

                }
                return remark;
            }
            catch (Exception e)
            {
                return remark;
            }
        }

        //public static void DeleteComments(Worksheet Sheet, Range range)
        //{
        //    /*
        //     * 删除comments
        //     */
        //    for (int i = 0; i < range.Rows.Count; i++)
        //    {
        //        for (int j = 0; j < range.Columns.Count; j++)
        //        {
        //            if (Sheet.Cells[i + range.Row, j + range.Column].Comment != null)
        //                Sheet.Cells[i + range.Row, j + range.Column].Comment.Delete();
        //        }
        //    }
        //}

        //public static void DeleteComments(Worksheet Sheet, Range range, AbstractReport<MonFinRptAsrepExt, AsrepExtItem> report)
        //{
        //    /*
        //     * 删除comments
        //     */
        //    for (int i = 0; i < range.Rows.Count; i++)
        //    {
        //        for (int j = 0; j < range.Columns.Count; j++)
        //        {
        //            if (Sheet.Cells[i + range.Row, j + range.Column].Comment != null)
        //            {
        //                Sheet.Cells[i + range.Row, j + range.Column].Comment.Delete();

        //                if (!report.CommentsList.Contains((i + range.Row) + "," + (j + range.Column)))
        //                {
        //                    report.CommentsList.Add((i + range.Row) + "," + (j + range.Column));
        //                }

        //                if (!report.UpdateColumns.Contains(j + range.Column))
        //                    report.UpdateColumns.Add(j + range.Column);
        //            }
        //        }
        //    }
        //}

        //public static void DeleteComments(Worksheet Sheet, Range range, AbstractReport<MonFinRptTpl, TplItem> report)
        //{
        //    /*
        //     * 删除comments
        //     */
        //    for (int i = 0; i < range.Rows.Count; i++)
        //    {
        //        for (int j = 0; j < range.Columns.Count; j++)
        //        {
        //            if (Sheet.Cells[i + range.Row, j + range.Column].Comment != null)
        //            {
        //                Sheet.Cells[i + range.Row, j + range.Column].Comment.Delete();

        //                if (!report.CommentsList.Contains((i + range.Row) + "," + (j + range.Column)))
        //                {
        //                    report.CommentsList.Add((i + range.Row) + "," + (j + range.Column));
        //                }

        //                if (!report.UpdateColumns.Contains(j + range.Column))
        //                    report.UpdateColumns.Add(j + range.Column);
        //            }
        //        }
        //    }
        //}

        //public static void DeleteComments(Worksheet Sheet, Range range, AbstractReport<MonFinRptBreakdown, BreakdownItem> report)
        //{
        //    /*
        //     * 删除comments
        //     */
        //    for (int i = 0; i < range.Rows.Count; i++)
        //    {
        //        for (int j = 0; j < range.Columns.Count; j++)
        //        {
        //            if (Sheet.Cells[i + range.Row, j + range.Column].Comment != null)
        //            {
        //                Sheet.Cells[i + range.Row, j + range.Column].Comment.Delete();

        //                if (!report.CommentsList.Contains((i + range.Row) + "," + (j + range.Column)))
        //                {
        //                    report.CommentsList.Add((i + range.Row) + "," + (j + range.Column));
        //                }

        //                if (!report.UpdateColumns.Contains(j + range.Column))
        //                    report.UpdateColumns.Add(j + range.Column);
        //            }
        //        }
        //    }
        //}

        ///// <summary>
        ///// set range format
        ///// </summary>
        ///// <param name="range"></param>
        ///// <param name="argFormat"></param>
        //public static void SetRangeFormat(Range range, int argFormat)
        //{
        //    try
        //    {
        //        range.HorizontalAlignment = XlHAlign.xlHAlignRight;

        //        string format = string.Empty;
        //        switch (argFormat)
        //        {
        //            case 0: format = "_(* #,##0_);_(* (#,##0);_(* \"0\"_);_(@_)"; break;
        //            case 2: format = "_(* #,##0.00_);_(* (#,##0.00);_(* \"0\"_);_(@_)"; break;
        //            case 3: format = "_(* #,##0.000_);_(* (#,##0.000);_(* \"0\"_);_(@_)"; break;
        //            case 4: format = "0.00%"; break;
        //            default: format = "_(* #,##0_);_(* (#,##0);_(* \"0\"_);_(@_)";
        //                break;
        //        }
        //        range.NumberFormat = format;
        //    }
        //    catch (Exception e)
        //    {
        //        throw new Exception(e.Message);
        //    }
        //}

        ///// <summary>
        ///// 填充科目样式
        ///// </summary>
        //public static void ApplyCellFormat(NormFinRptStyle FinRptStyle, Worksheet Sheet, string strRptCode, int endColumNum, int row, TemplateConfigure.Accp accp)
        //{
        //    if (FinRptStyle != null && FinRptStyle.items != null && FinRptStyle.items.Count > 0)
        //    {
        //        List<NormStyleItem> items = FinRptStyle.items;
        //        foreach (var source in items.OrderBy(x => x.pos))
        //        {
        //            //对空行的处理，直接跳过
        //            if (string.IsNullOrEmpty(source.cd))
        //            {
        //                row++;
        //                continue;
        //            }

        //            NormFinItem normFinItem = NormFinItemDao.GetFinItemByCode(source.cd, strRptCode);

        //            string colName = "";

        //            if (accp == TemplateConfigure.Accp.YTD)
        //            {
        //                colName = YTDConfig.DataStartCol;
        //            }

        //            if (accp == TemplateConfigure.Accp.CUR)
        //            {
        //                colName = CurLtmConfig.DataStartCol;
        //            }

        //            if (accp == TemplateConfigure.Accp.LTM)
        //            {
        //                colName = CurLtmConfig.DataStartCol;
        //            }

        //            //如果样式表里的科目在科目表里没有对应的科目，也要对单元格进行样式应用，只是默认小数位给0
        //            if (null == normFinItem)
        //            {
        //                SetRangeFormat(Sheet.Range[Sheet.Cells[row, colName],
        //                    Sheet.Cells[row, endColumNum]], 0);
        //            }
        //            else
        //            {
        //                SetRangeFormat(Sheet.Range[Sheet.Cells[row, colName],
        //                    Sheet.Cells[row, endColumNum]], normFinItem.digit);
        //            }

        //            row++;
        //        }
        //    }
        //}

        ///// <summary>
        ///// 填充科目样式
        ///// </summary>
        //public static void ApplyCellFormat(NormFinSamStyle FinRptStyle, Worksheet Sheet, string strRptCode, int endColumNum, int row, TemplateConfigure.Accp accp)
        //{
        //    if (FinRptStyle != null && FinRptStyle.items != null && FinRptStyle.items.Count > 0)
        //    {
        //        List<NormSamStyleItem> items = FinRptStyle.items;
        //        foreach (var source in items.OrderBy(x => x.pos))
        //        {
        //            //对空行的处理，直接跳过
        //            if (string.IsNullOrEmpty(source.cd))
        //            {
        //                row++;
        //                continue;
        //            }

        //            // NormFinItem normFinItem = NormFinItemDao.GetFinItemByCode(source.cd, strRptCode);

        //            string colName = "";

        //            if (accp == TemplateConfigure.Accp.YTD)
        //            {
        //                colName = YTDConfig.DataStartCol;
        //            }

        //            if (accp == TemplateConfigure.Accp.CUR)
        //            {
        //                colName = CurLtmConfig.DataStartCol;
        //            }

        //            if (accp == TemplateConfigure.Accp.LTM)
        //            {
        //                colName = CurLtmConfig.DataStartCol;
        //            }

        //            //如果样式表里的科目在科目表里没有对应的科目，也要对单元格进行样式应用，只是默认小数位给0
        //            if (source.typ == "1" && source.fi != "4")
        //            {
        //                SetRangeFormat(Sheet.Range[Sheet.Cells[row, colName],
        //                    Sheet.Cells[row, endColumNum]], 0);
        //            }
        //            else if (source.typ == "2" || source.typ == "3" || source.fi == "4")
        //            {
        //                SetRangeFormat(Sheet.Range[Sheet.Cells[row, colName],
        //                    Sheet.Cells[row, endColumNum]], 4);
        //            }

        //            row++;
        //        }
        //    }
        //}

        /// <summary>
        /// 填充科目样式
        /// </summary>
        //public static void ApplyCellFormat(NormFinSamStyle FinRptStyle, Worksheet Sheet, string strRptCode, int endColumNum, int row)
        //{
        //    if (FinRptStyle != null && FinRptStyle.items != null && FinRptStyle.items.Count > 0)
        //    {
        //        List<NormSamStyleItem> items = FinRptStyle.items;
        //        foreach (var source in items.OrderBy(x => x.pos))
        //        {
        //            //对空行的处理，直接跳过
        //            if (string.IsNullOrEmpty(source.cd))
        //            {
        //                row++;
        //                continue;
        //            }

        //            NormFinItem normFinItem = NormFinItemDao.GetFinItemByCode(source.cd, strRptCode);

        //            if (normFinItem != null)
        //                Utils.SetRangeFormat(Sheet.Range[Sheet.Cells[row, YTDConfig.ItemENameCol],
        //                    Sheet.Cells[row, endColumNum]], normFinItem.digit);

        //            row++;
        //        }
        //    }
        //}

        /// <summary>
        /// 封装科目并计算值
        /// </summary>
        //public static List<AsrepExtItem> PackAndCalItemValues(List<AsrepExtItem> items, Name2Value value, string value1orvalue2)
        //{
        //    if (value != null && value.Code != "" && value.State == 1)
        //    {
        //        bool MultiRelatived = false;

        //        foreach (var item in items)
        //        {
        //            if (item.Code == value.Code)
        //            {
        //                //计算最新值和原始值   
        //                if (value1orvalue2.ToUpper() == "NA" || value1orvalue2.ToUpper() == "NM")
        //                {
        //                    item.LastestValue = Convert.ToDouble(item.LastestValue).ToString();//NA和NM当做0来计算
        //                }
        //                else
        //                {
        //                    item.LastestValue = (Convert.ToDouble(item.LastestValue) + Convert.ToDouble(value1orvalue2)).ToString();
        //                }
        //                //将code和value写入集合中
        //                if (item.LstTrace == null) { item.LstTrace = new List<TraceItem>(); }
        //                item.LstTrace.Add(new TraceItem { Code = value.EnterCode, Value = value1orvalue2 });
        //                item.OriTrace = item.LstTrace;//初始化构造时将o与l赋值成相同值，后面如果是更改期则要修改为原始的值
        //                MultiRelatived = true;
        //            }
        //        }
        //        if (MultiRelatived == false)
        //        {
        //            AsrepExtItem item1 = null;
        //            if (value1orvalue2.ToUpper() == "NA" || value1orvalue2.ToUpper() == "NM")
        //            {
        //                item1 = new AsrepExtItem
        //                {
        //                    Code = value.Code,
        //                    LastestValue = "0",
        //                    OriginalValue = "0",
        //                };
        //            }
        //            else
        //            {
        //                item1 = new AsrepExtItem
        //                                         {
        //                                             Code = value.Code,
        //                                             LastestValue = value1orvalue2,
        //                                             OriginalValue = value1orvalue2,
        //                                         };
        //            }
        //            if (item1.LstTrace == null) { item1.LstTrace = new List<TraceItem>(); }
        //            item1.LstTrace.Add(new TraceItem { Code = value.EnterCode, Value = value1orvalue2 });
        //            item1.OriTrace = item1.LstTrace;//初始化构造时将o与l赋值成相同值，后面如果是更改期则要修改为原始的值
        //            items.Add(item1);

        //        }
        //    }

        //    return items;
        //}

        /// <summary>
        /// 计算多个TraceItem的值
        /// </summary>      
        public static double CalTraceItemValues(List<TraceItem> argTraceItems)
        {
            if (argTraceItems.Count > 1)
            {
                double result = 0;
                foreach (var item in argTraceItems)
                {
                    if (IsNumber(item.Value))
                    {
                        result += Convert.ToDouble(item.Value);
                    }
                }
                return result;
            }
            else if (argTraceItems.Count == 1)
            {
                if (!IsNumber(argTraceItems[0].Value))
                {
                    return 0;
                }
                else
                {
                    return Convert.ToDouble(argTraceItems[0].Value);
                }
            }
            else
            {
                return 0;
            }
        }
        /// <summary>
        /// Analysis code(apply into 2.1.1 so far)
        /// </summary>  
        public static CodeCnnRow AnalysisCode(string argCustomCode)
        {
            if (!string.IsNullOrEmpty(argCustomCode))
            {
                if (argCustomCode.Contains(';'))
                {
                    string[] arguments = argCustomCode.Split(';');
                    CodeCnnRow result = new CodeCnnRow();
                    result.Code = arguments[0];
                    if (IsNumber(arguments[1])) { result.Row = Convert.ToInt32(arguments[1]); }
                    return result;
                }
                //不包含的表添加科目，只有code
                else
                {
                    return new CodeCnnRow { Code = argCustomCode, Row = 0 };
                }
            }
            else return new CodeCnnRow { Code = "" };
        }

        /// <summary>
        /// 对src字段的赋值的多种情况
        /// </summary>
        /// <param name="EnterSrc">录入的src</param>
        /// <param name="OriSrc">原始的src</param>
        /// <returns>重新构造后的src</returns>
        public static List<string> CombineSrc(List<string> EnterSrc, List<string> OriSrc)
        {
            List<string> delEnternullstr = new List<string>();
            List<string> delOrinullstr = new List<string>();
            //去掉录入src的空字符,保证录入的src正确
            foreach (string enteritem in EnterSrc)
            {
                if (!string.IsNullOrEmpty(enteritem))
                {
                    delEnternullstr.Add(enteritem);
                }
            }
            delEnternullstr = delEnternullstr.Distinct().ToList();
            foreach (string oriitem in OriSrc)
            {
                if (!string.IsNullOrEmpty(oriitem))
                {
                    delOrinullstr.Add(oriitem);
                }
            }
            delOrinullstr = delOrinullstr.Distinct().ToList();
            if (delEnternullstr.Count == 0) { return delOrinullstr; }
            //确认业务上只会从录入区输入一个，不会输入多个
            else if (delEnternullstr.Count == 1)
            {
                if (delOrinullstr.Count == 0) { return delEnternullstr; }
                else if (delOrinullstr.Count == 1) { delOrinullstr.Add(delEnternullstr[0]); return delOrinullstr.Distinct().ToList(); }
                else if (delOrinullstr.Count == 2)
                {
                    List<string> newsrc = new List<string>();
                    newsrc.Add(delOrinullstr[1]);
                    newsrc.Add(delEnternullstr[0]);
                    return newsrc.Distinct().ToList();
                }
            }
            else if (delEnternullstr.Count == 2)
            {
                return delEnternullstr.Distinct().ToList();
            }
            return delEnternullstr.Distinct().ToList();
        }

        //public static void ForeachTree(TreeNode node, TreeNode curNode, NormFinItem item, ref bool matched)
        //{
        //    if (!matched)
        //    {
        //        if (item != null)
        //        {
        //            foreach (TreeNode treeNode in node.Nodes)
        //            {
        //                if (item.name.szh == treeNode.Text)
        //                {
        //                    //除了名字还得按code比较，这是由于会出现同时匹配公司和公共的时候，优先匹配公司，但是样式可能是公共的code，这就出现两棵树上的code不匹配，但是名字相同
        //                    Name2Value BDName2Value = curNode.Tag as Name2Value;
        //                    if (BDName2Value != null)
        //                    {

        //                        if ((treeNode.Tag as Name2Value).Code == BDName2Value.Code)
        //                        {
        //                            curNode.ImageIndex = 2;
        //                            curNode.SelectedImageIndex = 2;

        //                            BDName2Value.State = 1;
        //                            //BDName2Value.Code = item.code; //(treeNode.Tag as Name2Value).Code;

        //                            curNode.Tag = BDName2Value;

        //                            //Name2Value oriTreeTag = curNode.Tag as Name2Value;
        //                            //oriTreeTag.Name = GetStandardName(curNode.Text);

        //                            //treeNode.Tag = oriTreeTag;

        //                            matched = true;

        //                            break;
        //                        }
        //                    }
        //                }

        //                ForeachTree(treeNode, curNode, item, ref matched);
        //            }
        //        }
        //    }
        //}

        public static string GetStandardName(string name)
        {
            string result = string.Empty;
            if (name != "")
            {
                // name.IndexOf('[').Split('[')
                result = name.Substring(name.IndexOf('['));
                if (result.Contains('[') || result.Contains(']'))
                {
                    result = result.Replace("[", "").Replace("]", "");
                }
                //result = name.Split(' ')[1].Replace("[", "").Replace("]", "");
            }
            return result;
        }

        public static string GetNoRowCode(string argCode)
        {
            string[] strArray = argCode.Split(':');
            if (strArray.Length == 3)
            {
                return strArray[0];
            }
            return argCode;

        }

        public static int GetNoCodeRow(string argCode)
        {
            string[] strArray = argCode.Split(':');
            if (strArray.Length == 3)
            {
                return Convert.ToInt32(strArray[1]);
            }
            return 0;

        }

        //public static string GetAsReportRpt(string argRpt)
        //{
        //    string strAsRpt = string.Empty;
        //    switch (argRpt)
        //    {
        //        case YTDConfig.TPLRptCode_2_1_2:
        //        case YTDConfig.TPLRptCode_2_1_3:
        //            strAsRpt = YTDConfig.RptCode_2_1_1;
        //            break;
        //        case YTDConfig.TPLRptCode_2_2_2:
        //            strAsRpt = YTDConfig.RptCode_2_2_1;
        //            break;
        //        case YTDConfig.TPLRptCode_2_3_2:
        //            strAsRpt = YTDConfig.RptCode_2_3_1;
        //            break;
        //        default:
        //            throw new Exception("该Tpl Rpt 不正确!");
        //    }
        //    return strAsRpt;

        //}

        /// <summary>
        /// 财年合法判断
        /// </summary>
        /// <param name="argFY"></param>
        /// <returns></returns>
        public static bool IsFinacialYear(string argFY)
        {
            Regex regex = new Regex("\\d{1,2}-\\d{1,2}");
            return regex.IsMatch(argFY);
        }

        public static bool IsBSerialTable(string rpt)
        {
            bool Btable = rpt.StartsWith("I")
                          || rpt.StartsWith("B")
                          || rpt.StartsWith("T");

            //switch (rpt)
            //{
            //    case YTDConfig.TPLRptCode_B2111: Btable = true; break;
            //    case YTDConfig.TPLRptCode_B2161: Btable = true; break;
            //    case YTDConfig.TPLRptCode_B251: Btable = true; break;
            //    case YTDConfig.TPLRptCode_B311: Btable = true; break;
            //    case YTDConfig.TPLRptCode_B321: Btable = true; break;
            //    case YTDConfig.TPLRptCode_B331: Btable = true; break;
            //    case YTDConfig.TPLRptCode_B341: Btable = true; break;
            //    case YTDConfig.TPLRptCode_B351: Btable = true; break;
            //    case YTDConfig.TPLRptCode_B361: Btable = true; break;
            //    case YTDConfig.TPLRptCode_B411: Btable = true; break;
            //    case YTDConfig.TPLRptCode_B421: Btable = true; break;
            //    case YTDConfig.TPLRptCode_B511: Btable = true; break;
            //    case YTDConfig.TPLRptCode_B711: Btable = true; break;
            //    case YTDConfig.TPLRptCode_B721: Btable = true; break;
            //    case YTDConfig.TPLRptCode_IN2111: Btable = true; break;
            //    case YTDConfig.TPLRptCode_IN2121: Btable = true; break;
            //    case YTDConfig.TPLRptCode_T451: Btable = true; break;
            //    case YTDConfig.TPLRptCode_T4101: Btable = true; break;
            //    case YTDConfig.TPLRptCode_S341: Btable = true; break;
            //    case YTDConfig.TPLRptCode_S351: Btable = true; break;
            //    case YTDConfig.TPLRptCode_S521: Btable = true; break;
            //    default:
            //        break;
            //}
            return Btable;
        }

        /// <summary>
        /// 给数据解锁
        /// </summary>
        /// <param name="argTick"></param>
        /// <param name="argRpt"></param>
        /// <param name="argConsolidation"></param>
        /// <param name="argType"></param>
        /// <param name="argName"></param>
        /// <param name="argCode"></param>
        //public static string UnLock(string argTick, string argRpt, int argConsolidation, int argType, string argName, string argCode)
        //{
        //    string strName = string.Empty;
        //    if (FinLockDao.IsUnLocked(argRpt, argTick, argConsolidation, argType, SystemConfigHelper.Environment, out strName))
        //    {
        //        if (strName != argName)
        //        {
        //            throw new Exception(string.Format("该报表已被{0}独占方式编辑,请以只读方式访问或联系管理员!", strName));
        //        }
        //        return null;
        //    }
        //    else
        //    {
        //        NormFinLockRecord insert = CreateLockEntity(argRpt, argTick, argConsolidation, argType, argName, argCode);//将迁出记录写入记录集中
        //        return FinLockDao.InsertLockedRecords(insert);
        //    }

        //}

        /// <summary>
        /// 还原锁定状态
        /// </summary>
        /// <param name="argTick"></param>
        /// <param name="argRpt"></param>
        /// <param name="argConsolidation"></param>
        /// <param name="argType"></param>
        //public static string Lock(string argTick, string argRpt, int argConsolidation, int argType)
        //{
        //    return FinLockDao.ReleaseLock(argRpt, argTick, argConsolidation, argType, SystemConfigHelper.Environment);
        //}

        /// <summary>
        /// 打包实例
        /// </summary>
        /// <param name="argRpt"></param>
        /// <param name="ticker"></param>
        /// <param name="consolidation"></param>
        /// <param name="type"></param>
        /// <param name="argName"></param>
        /// <param name="argCode"></param>
        /// <returns></returns>
        //private static NormFinLockRecord CreateLockEntity(string argRpt, string ticker, int consolidation, int type, string argName, string argCode)
        //{
        //    NormFinLockRecord entity = new NormFinLockRecord();
        //    entity.rpt = argRpt;
        //    entity.tik = ticker;
        //    entity.consolidation = consolidation;
        //    entity.typ = type;
        //    entity.username = argName;
        //    entity.usercode = argCode;
        //    entity.upt = DateTime.Now;
        //    entity.environment = SystemConfigHelper.Environment;

        //    return entity;
        //}


        /// <summary>
        /// 撤销保护工作薄
        /// </summary>
        /// <param name="sheet"></param>
        /// <param name="password"></param>
        //public static void UnLockSheet(this Worksheet sheet)
        //{
        //    if (sheet.ProtectContents)
        //    {
        //        sheet.Unprotect("1");
        //    }
        //}
        /// <summary>
        /// 保护工作薄
        /// </summary>
        /// <param name="sheet"></param>
        /// <param name="password"></param>
        //public static void LockSheet(this Worksheet sheet)
        //{
        //    try
        //    {
        //        if (sheet!=null&&!sheet.ProtectContents)
        //        {
        //            object oMissing = System.Reflection.Missing.Value;
        //            //sheet.Protect(Config.Configuration.Password, false, true, true, true,true,true,true,oMissing,oMissing,oMissing,oMissing,oMissing,oMissing,oMissing,oMissing);
        //            sheet.Protect("1", false, true, true, true, true, true, true, false, false, false, false, false, false, false, false);
        //            sheet.EnableOutlining = true;
        //        }
        //    }
        //    catch (System.Runtime.InteropServices.COMException)
        //    {

        //    }
        //    catch (Exception ex)
        //    {
        //        throw;
        //    }
           
        //}


        /// <summary>
        /// 判断数据内是否包含该Code
        /// </summary>
        /// <param name="argObj"></param>
        /// <param name="argCode"></param>
        /// <returns></returns>
        public static bool IsContains(object[] argObj, string argCode, out int argIndex)
        {
            argIndex = -1;
            for (int i = 0; i < argObj.Length; i++)
            {
                if (argObj[i] != null && argObj[i].ToString() == argCode)
                {
                    argIndex = i;
                    return true;
                }
            }

            return false;
        }

        /// <summary>
        /// 改nature 明细用
        /// </summary>
        /// <param name="code"></param>
        /// <param name="nature"></param>
        /// <returns></returns>
        //public static string GetCodeWithRule(string code, int nature)
        //{
        //    string newCode = code;

        //    if (nature == 0)
        //    {
        //        return code;
        //    }


        //    if (code != "")
        //    {
        //        string[] plit = code.Split('_');

        //        if (plit.Length > 0 && plit.Length == 4)
        //        {
        //            newCode = string.Format("{0}_{1}_{2}_{3}", plit[0], plit[1], nature, plit[3]);
        //        }
        //        else
        //        {
        //            MessageBox.Show(string.Format("{0}有科目的Code不符合数据标准，应该类似于in_tpl_1_15这种结构", code));
        //        }
        //    }
        //    return newCode;
        //}


        /// <summary>
        /// 根据Code取得Nature
        /// </summary>
        /// <param name="argCode"></param>
        /// <returns></returns>
        public static string GetNature(string argCode)
        {
            string[] plit = argCode.Split('_');

            if (plit.Length > 0 && plit.Length == 4)
            {
                return plit[2];
            }
            return "";
        }

        /// <summary>
        /// 将YES和NO转换成 Bool
        /// </summary>
        /// <param name="argString"></param>
        /// <returns></returns>
        public static bool ConvertToBool(string argString)
        {
            if (argString.ToLower() == "yes")
            {
                return true;
            }
            else if (argString.ToLower() == "no")
            {
                return false;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 将字符串转换成Double ,NM NA则表示0
        /// </summary>
        /// <param name="argValue"></param>
        /// <returns></returns>
        public static double ConverToDouble(string argValue)
        {
            if (string.IsNullOrEmpty(argValue))
            {
                return 0;
            }
            if (argValue == "NM" || argValue == "NA")
            {
                return 0;
            }

            return double.Parse(argValue);
        }

        /// <summary>
        /// 去掉string的无效数字 是NM NA 的话 就返回原值
        /// </summary>
        /// <param name="argValue"></param>
        /// <returns></returns>
        public static string ConvertDigit(string argValue)
        {
            if (argValue != null)
            {
                double dbValue = -1;
                if (!double.TryParse(argValue.TrimEnd('0'), out dbValue))
                {
                    return argValue.ToString();
                }
                return dbValue.ToString();
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// 删除ListObject的内容
        /// </summary>
        //public static void ClearContents(Microsoft.Office.Tools.Excel.ListObject list)
        //{
        //    for (int i = 1; i <= list.ListRows.Count; i++)
        //    {
        //        var row = list.ListRows[i];
        //        row.Range.ClearContents();
        //    }
        //}
    }

    /// <summary>
    /// NormStyleItem 比较接口
    /// </summary>
    /// 
    public class MonTplItemComparer : IEqualityComparer<TplItem>
    {
        public bool Equals(TplItem x, TplItem y)
        {
            if (object.ReferenceEquals(x, y))
            {
                return true;
            }
            if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
            {
                return false;
            }
            return x.Code == y.Code;

        }

        public int GetHashCode(TplItem tplitem)
        {
            //Check whether the object is null
            if (Object.ReferenceEquals(tplitem, null)) return 0;

            //Get hash code for the Name field if it is not null.
            int hashitemCode = tplitem.Code == null ? 0 : tplitem.Code.GetHashCode();

            //Calculate the hash code for the product.
            return hashitemCode;
        }
    }

    public class MonextItemComparer : IEqualityComparer<BreakdownItem>
    {
        public bool Equals(BreakdownItem x, BreakdownItem y)
        {
            if (object.ReferenceEquals(x, y))
            {
                return true;
            }
            if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
            {
                return false;
            }
            return x.Code == y.Code;

        }

        public int GetHashCode(BreakdownItem breakdownitem)
        {
            //Check whether the object is null
            if (Object.ReferenceEquals(breakdownitem, null)) return 0;

            //Get hash code for the Name field if it is not null.
            int hashitemCode = breakdownitem.Code == null ? 0 : breakdownitem.Code.GetHashCode();

            //Calculate the hash code for the product.
            return hashitemCode;
        }
    }

}
